﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SMS.Entities;
using SMS.DAL.DAHelpers;

namespace SMS.DAL
{
    public class SalesHistoryDA : BaseDA<SaleHistory>
    {

        public override SaleHistory SaveObject(string userName, SaleHistory tObject)
        {
            try
            {
                dbHelper.AddParameter("@Sale_ID", tObject.Sale_ID);
                dbHelper.AddParameter("@Customer_ID", tObject.Customer.Customer_ID);
                dbHelper.AddParameter("@TotalSellingPrice", tObject.TotalSellingPrice);
                dbHelper.AddParameter("@ActualSelliingPrice", tObject.ActualSelliingPrice);
                dbHelper.AddParameter("@BuyingPrice", tObject.BuyingPrice);
                dbHelper.AddParameter("@Discount", tObject.Discount);
                dbHelper.AddParameter("@Selling_Date", tObject.Selling_Date);
                dbHelper.AddParameter("@SalesMan", tObject.SalesMan.SalesMan_ID);
                dbHelper.AddParameter("@UserName", userName);
                dbHelper.AddParameter("@Counter_ID", tObject.Counter_ID);
                dbHelper.AddParameter("@Is_Paid", tObject.Is_Paid);
                dbHelper.AddParameter("@Remarks", string.IsNullOrWhiteSpace(tObject.Remarks) ? string.Empty : tObject.Remarks);
                dbHelper.AddParameter("@Paid_Amount", tObject.PaidAmount);
                dbHelper.AddParameter("@IsLive", tObject.IsLive);
                object objectId = dbHelper.ExecuteScaler("USP_INS_UPDATE_SALESHISTORY", System.Data.CommandType.StoredProcedure, System.Data.ConnectionState.Closed);
                if (Convert.ToInt32(objectId) > 0)
                    tObject.Sale_ID = Convert.ToInt32(objectId);
                var salesdetailDA = new SalesDetailDA();
                foreach (var item in tObject.SalesDetailList)
                {
                    item.SalesHistory = tObject;
                    salesdetailDA.SaveObject(userName, item);
                    item.SalesHistory = null;
                }
                LogActivity(userName, string.Format("SalesHistory Saved with ID {0}", tObject.Sale_ID), tObject);
                return tObject;
            }
            catch (Exception ex)
            {
                LogException(userName, ex, tObject);
                throw new Exception("Error Occured while Saving SalesHistory");
            }

        }

        public override bool DeleteObject(string userName, SaleHistory tObject)
        {
            throw new NotImplementedException();
        }

        public override List<SaleHistory> GetObjectList(string userName, DateTime fromDate, DateTime toDate)
        {
            System.Data.IDataReader reader = null;
            try
            {
                dbHelper.AddParameter("@FromDate", fromDate);
                dbHelper.AddParameter("@ToDate", toDate);
                reader = dbHelper.ExecuteReader("USP_SELECT_SALESHISTORYLIST", System.Data.CommandType.StoredProcedure, System.Data.ConnectionState.Closed);
                List<SaleHistory> history = new List<SaleHistory>();
                while (reader.Read())
                    history.Add(GetSaleHistoryObject(reader));
                reader.Close();
                LogActivity(userName, string.Format("SaleHistory list loaded from {0} to {1}", fromDate, toDate), null);
                return history;
            }
            catch (Exception ex)
            {
                LogException(userName, ex, null);
                throw;
            }


        }

        public SaleHistory GetSaleHistoryDetail(string userName, int Sale_ID)
        {
            System.Data.IDataReader reader = null;
            try
            {
                dbHelper.AddParameter("@Sales_ID", Sale_ID);
                reader = dbHelper.ExecuteReader("", System.Data.CommandType.StoredProcedure, System.Data.ConnectionState.Closed);

                SaleHistory saleObject = null;
                if (reader.Read())
                {
                    saleObject = GetSaleHistoryObject(reader);
                    if (reader.NextResult())
                    {
                        saleObject.SalesDetailList = new System.Collections.ObjectModel.ObservableCollection<SaleDetail>();
                        while (reader.Read())
                        {
                            saleObject.SalesDetailList.Add(GetSaleDetailObject(reader));
                        }
                    }
                }
                reader.Close();
                LogActivity(userName, string.Format("SaleHistory detail loaded for ID {0}", saleObject == null ? 0 : saleObject.Sale_ID), saleObject);
                return saleObject;
            }
            catch (Exception ex)
            {
                if (reader != null)
                    reader.Close();
                LogException(userName, ex, null);
                return null;
            }

        }

        private SaleHistory GetSaleHistoryObject(System.Data.IDataReader reader)
        {
            SaleHistory history = new SaleHistory();
            int i = 0;
            history.Sale_ID = reader.GetInt32(i++);
            history.Customer = new Customer { Customer_ID = reader.GetInt32(i++) };
            history.TotalSellingPrice = reader.GetDecimal(i++);
            history.ActualSelliingPrice = reader.GetDecimal(i++);
            history.BuyingPrice = reader.GetDecimal(i++);
            history.Discount = reader.GetDecimal(i++);
            history.Selling_Date = reader.GetDateTime(i++);
            history.SalesMan = new SalesManDetail { SalesMan_ID = reader.GetInt32(i++) };
            history.Counter_ID = reader.GetInt32(i++);
            history.Is_Paid = reader.GetBoolean(i++);
            history.Remarks = reader.GetString(i++);
            return history;
        }

        private SaleDetail GetSaleDetailObject(System.Data.IDataReader reader)
        {
            SaleDetail detail = new SaleDetail();
            int i = 0;
            detail.ProductStockWise = new ProductStockWise { Product_Stock_ID = reader.GetInt32(i++) };
            detail.SellingUnitPrice = reader.GetDecimal(i++);
            detail.BilledAmount = reader.GetDecimal(i++);
            detail.Discount = reader.GetDecimal(i++);
            return detail;
        }

        public override List<SaleHistory> SearchObject(string userName, string SearchText)
        {
            throw new NotImplementedException();
        }
    }

    public class SalesDetailDA : BaseDA<SaleDetail>
    {

        public override SaleDetail SaveObject(string userName, SaleDetail tObject)
        {
            try
            {
                GetNewDBHelper();
                dbHelper.AddParameter("@SaleDetail_ID", tObject.SaleDetail_ID);
                dbHelper.AddParameter("@Sales_ID", tObject.SalesHistory.Sale_ID);
                dbHelper.AddParameter("@ProductStockWiseID", tObject.ProductStockWise.Product_Stock_ID);
                dbHelper.AddParameter("@SellingUnitPrice", tObject.SellingUnitPrice);
                dbHelper.AddParameter("@BilledAmount", tObject.BilledAmount);
                dbHelper.AddParameter("@TotalAmount", tObject.TotalAmount);
                dbHelper.AddParameter("@Discount", tObject.Discount);
                dbHelper.AddParameter("@IsRetail", tObject.IsRetail);
                if (tObject.IsRetail)
                {
                    dbHelper.AddParameter("@Quantity", Math.Round(tObject.Quantity / (tObject.ProductStockWise.SubQuantity / tObject.ProductStockWise.Quantity), 2));
                }
                else
                    dbHelper.AddParameter("@Quantity", tObject.Quantity);
                dbHelper.AddParameter("@IsLive", tObject.IsLive);
                object objectKey = dbHelper.ExecuteScaler("USP_INSERT_UPDATE_SALESDETAIL", System.Data.CommandType.StoredProcedure, System.Data.ConnectionState.Closed);
                if (objectKey != DBNull.Value && Convert.ToInt32(objectKey) > 0)
                    tObject.SaleDetail_ID = Convert.ToInt32(objectKey);
                LogActivity(userName, string.Format("SalesHistory Saved with ID {0}", tObject.SaleDetail_ID), tObject);
                return tObject;
            }
            catch (Exception ex)
            {
                LogException(userName, ex, tObject);
                throw new Exception("Error occured while Saving SalesDetail");
            }

        }

        public override bool DeleteObject(string userName, SaleDetail tObject)
        {
            throw new NotImplementedException();
        }

        public override List<SaleDetail> GetObjectList(string userName, DateTime fromDate, DateTime toDate)
        {
            throw new NotImplementedException();
        }

        public override List<SaleDetail> SearchObject(string userName, string SearchText)
        {
            throw new NotImplementedException();
        }
    }



}
